package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.EncryptUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 分享记录
 * </p>
 *
 * @author chenxuebin
 * @since 2019-03-21
 */
@Controller
public class ShareController {

    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);

    @Autowired
    private IShareService shareService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private INewsService newsService;
    @Autowired
    private IGoodsQunzfService goodsQunzfService;

    @RequestMapping("/api/share/list")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "status", required = false) String status,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                      HttpServletRequest req) {
        Jinfo info = new Jinfo();
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        page = shareService.selectPage(page, new EntityWrapper<Share>()
                .eq("uid", ObjectUtil.getUid())
                .eq("state", 1));
        info.setInfo(page.getRecords());
        return info;
    }

    @RequestMapping("/api/share/add")
    @ResponseBody
    public Jinfo shareAdd(Share share) {
        Jinfo info = new Jinfo();
//        try {
//            String path = java.net.URLDecoder.decode(share.getPath(), "UTF-8");
//            share.setPath(path);
//        } catch (Exception e) {
//        }

        // 解密
//        String result = ObjectUtil.wxdectypt(encryptedData,iv,code);
//        JSONObject json = ObjectUtil.wxdectypt(encryptedData, iv, code);
//        JSONObject json = JSON.parseObject(result);
//        if (json != null) share.setGroupid(json.getString("openGId"));

        User user = redisService.getUser();
        if (user != null) {
            share.setNickname(user.getNickName());
            share.setAvatarpic(user.getAvatarPic());
        }
        String path = "";
        try {
            path = java.net.URLDecoder.decode(share.getPath(), "UTF-8");
        } catch (Exception e) {
            logger.error("======shareAdd error", e);
        }
        path = ObjectUtil.sortQuery(share.getPath());
        logger.debug("----------------------------------------------------------------------------path=" + path);
        if (path.indexOf("?") < 0) {
            Date now = new Date();
            path += "?ts=" + now.getTime();
        }
        logger.debug("----------------------------------------------------------------------------path=" + path);
        String page = path.substring(0, path.indexOf("?"));
        Map<String, String> pathmap = ObjectUtil.sortQueryMap(path);
        Long ywid = 0l;
        if (pathmap.containsKey("ori")) {
            String ori = pathmap.get("ori");
            if (!Strings.isNullOrEmpty(ori) && ori.split("_").length == 4
                    && ori.split("_")[3].length() > 0) {
                try {
                    ywid = Long.parseLong(ori.split("_")[3]);
                } catch (Exception e) {
                    logger.error("---------share ywid parse error", e);
                }

                Goods goods = goodsService.selectById(ywid);
                if (path.indexOf("/goods")>0 && goods != null) {
                    share.setYwid(ywid);
                    GoodsQunzf goodsQunzf = goodsQunzfService.selectById(ywid);
                    share.setQfjiang(goodsQunzf == null || goodsQunzf.getState() != 1 ? null : 1);
                }

                News news = newsService.selectById(ywid);
                if ((path.indexOf("/qntsp")>0||path.indexOf("/newsdetail")>0) && news != null) {
                    News nnews = new News();
                    nnews.setSharecout(news.getSharecout()+1);
                    nnews.setModifytime(new Date());
                    nnews.setId(news.getId());
                    nnews.updateById();
                }
            }
        }

        String pathguid = EncryptUtil.md5(path);
        share.setPath(path);
        share.setPathguid(pathguid);

        share.setPage(page);
        share.setViews(0);
        share.setBuys(0);
        share.setRegists(0);
        share.setSharedate(DateUtil.getToday());

        share.setCreatetime(new Date());
        share.setGuid(ObjectUtil.getGuid());
        share.setUid(ObjectUtil.getUid());
        share.setMid(ObjectUtil.getMid());
        share.setMpid(ObjectUtil.getMpid());
        share.insert();

        // 返回今日抽奖分享
        int todayshare = shareService.selectCount(new EntityWrapper<Share>()
                .eq("uid", ObjectUtil.getUid())
                .eq("sharedate", DateUtil.getToday())
                .like("path", "/pages/zhuanpan/zhuanpan/")
        );
        info.setInfo(todayshare);

        //share.getpath
        if (page.equals("/pages/qntsp/qntsp")) {

        }

        return info;
    }

    @RequestMapping("/api/share/modify")
    @ResponseBody
    public Jinfo shareUpdate(HttpServletRequest req,
                             Share share) {
        Jinfo info = new Jinfo();
        share.setModifytime(new Date());
        share.updateById();
        return info;
    }

    @RequestMapping("/api/share/detail")
    @ResponseBody
    public Jinfo getShareDetailById(@RequestParam("token") String token,
                                    @RequestParam("id") long id, HttpServletRequest req
    ) {
        Jinfo info = new Jinfo();
        Share share = shareService.selectById(id);
        info.setInfo(share);
        return info;
    }
}
